﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentNHibernate.Cfg;
using NHibernate;
using FluentNHibernate.Cfg.Db;
using NHibernate.Cfg;
using Spaanjaars.ContactManager.Repository.NH.SessionStorage;

namespace Spaanjaars.ContactManager.Repository.NH
{
    public class SessionFactory
    {
        private static ISessionFactory _SessionFactory;

        private static void Init()
        {

            _SessionFactory = Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2005.ConnectionString(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|ContactsDB.mdf;Integrated Security=True;User Instance=True"))
                .Mappings(map => map.FluentMappings.AddFromAssemblyOf<SessionFactory>())
                .BuildSessionFactory();
            
            
            //Configuration config = new Configuration();
            //config.AddAssembly("Spaanjaars.ContactManager.Repository.NH");
            
            //config.Configure();

            //_SessionFactory = config.BuildSessionFactory();
        }

        private static ISessionFactory GetSessionFactory()
        {
            if (_SessionFactory == null)
                Init();

            return _SessionFactory;
        }

        private static ISession GetNewSession()
        {
            return GetSessionFactory().OpenSession();
        }

        public static ISession GetCurrentSession()
        {
            ISessionStorageContainer _sessionStorageContainer = SessionStorageFactory.GetStorageContainer();

            ISession currentSession = _sessionStorageContainer.GetCurrentSession();

            if (currentSession == null)
            {
                currentSession = GetNewSession();
                _sessionStorageContainer.Store(currentSession);
            }

            return currentSession;
        }
    }
}
